<?php

namespace app\admin\controller\goods;

use app\common\controller\AdminController;
use app\common\service\RedisService;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="商品货架（平台仓库）")
 */
class Shelves extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\GoodsShelves();
        
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model
                ->where($where)
                ->where("state <> -1")
                ->count();
            $list = $this->model
                ->where($where)
                ->where("state <> -1")
                ->page($page, $limit)
                ->order($this->sort)
                ->select();

            //
            foreach($list as &$val){
                $category = Db::name("goods_category")->find($val['cid']);
                $val['category_name'] = $category ? $category['name'] : "--";

                $val['view_price'] = $val['price']/100 . "元";
                $val['img'] = implode("|",json_decode($val['img'],true));
            }

            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            
            return json($data);
        }
        return $this->fetch();
    }


    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                
                $lastid = $this->model->max("id");
                $post['code'] = "C00A".($lastid+1);
                $post['img'] = json_encode(explode("|", $post['img']));
                $post['price'] = $post['price'] * 100;//金额为分
                //保存数据
                $save = $this->model->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败:'.$e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $category = Db::name("goods_category")->where(['state' => 1])->select();
        $this->assign("category", $category);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                $post['img'] = json_encode(explode("|", $post['img']));
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        //商品分类
        $category = Db::name("goods_category")->where(['state' => 1])->select();
        $this->assign("category", $category);
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="删除")
     */
    public function delete($id)
    {
        $this->checkPostRequest();
        $row = $this->model->whereIn('id', $id)->select();
        $row->isEmpty() && $this->error('数据不存在');
        try {
            $save = $row->update(['id' => $id, "state" => -1]);
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    /**
     * @NodeAnotation(title="推送货架商品")
     */
    public function sync()
    {
        // TODO  后期再做
        // TODO  json_encode : JSON_UNESCAPED_UNICODE

        //推送货架商品
        $data = Db::query("SELECT * FROM sy_goods_shelves WHERE state=1 ORDER BY id DESC", []);
        $cList = Db::query("SELECT * FROM sy_goods_category WHERE state=1 AND id>0 ORDER BY id DESC", []);

        $cListDD = array_column($cList, null, 'id') ;

        // 删除原先的键
        $delKeys = RedisService::select(3)->keys( self::KEYS['SHELVES_GOODS'] . '*');
        if ( count($delKeys) > 0) {
            RedisService::select(3)->del($delKeys);
        }

        // 全部分类列表中添加
        for ($i = 0; $i < count($data); $i++) {
            $map[ $data[$i]['id'] ] = json_encode($data[$i], JSON_UNESCAPED_UNICODE ) ;
            RedisService::select(3)->hmSet( self::KEYS['SHELVES_GOODS'] . '0', $map);
            $new[ $data[$i]['cid'] ][] = $data[$i] ;
        }
        // 各个分类中添加
        foreach($new as $k => $item){
            foreach($item as &$val ) {
                $map[ $val['id'] ] = json_encode($val, JSON_UNESCAPED_UNICODE ) ;
                RedisService::select(3)->hmSet( self::KEYS['SHELVES_GOODS'] . $k , $map);
            }
        }
        // 清除计数器
        RedisService::select(3)->del( self::KEYS['SHELVES_GOODS_COUNTER'] );
        // 更新计数器
        for ( $i = 0; $i < count($data); $i++) {
            $map[ $data[$i]['id'] ] = intval($data[$i]['count']);
            RedisService::select(3)->HMSET( self::KEYS['SHELVES_GOODS_COUNTER'], $map );
        }
        // 清除Banner  保留banner
        #RedisService::select(3)->del( self::KEYS['BANNER_LIST']);

    }

}